package com.example.RemindMe;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class EditAlarmActivity extends Activity {

	TimePicker tp;
	String id;
	SharedPreferences settings;
	String datetime;
	Calendar cal;
	Date date;
	long datemilis;
	CalendarView cv;
	EditText description;
	Spinner snooze;
	String uriSelected;
	Button btnRingtone;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setRequestedOrientation(1);
		setContentView(R.layout.activity_editalarm);
		btnRingtone = (Button) findViewById(R.id.button2);
		tp = (TimePicker) findViewById(R.id.timePicker2);
		tp.setIs24HourView(true);
		cv = (CalendarView) findViewById(R.id.calendarView2);

		settings = getSharedPreferences("alarms", 0);
		Bundle extras = getIntent().getExtras();

		id = extras.getString("selected");
		System.out.println(id);
		String[] dataArray = settings.getString(id, "0").split(";");
		datetime = dataArray[0];
		Uri uriPre = Uri.parse(dataArray[2]);
		Ringtone titelPre = RingtoneManager.getRingtone(this, uriPre);
		btnRingtone.setText(titelPre.getTitle(this));
		uriSelected = dataArray[2];

		description = (EditText) findViewById(R.id.editText1);
		snooze = (Spinner) findViewById(R.id.spinner2);
		String data = settings.getString("" + id, "0");

		String[] arrayDate = data.split(";");
		description.setText(arrayDate[1]);
		snooze.setSelection(Integer.parseInt(arrayDate[3]));

		SimpleDateFormat sdfToDate = new SimpleDateFormat("dd.MM.yyyy HH:mm");
		try {
			date = sdfToDate.parse(datetime);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Datum" + date);
		cal = Calendar.getInstance();
		cal.setTime(date);
		cv.setDate(date.getTime());
		tp.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
		tp.setCurrentMinute(cal.get(Calendar.MINUTE));

	}

	public void save(View v) {
		save();
	}

	/**
	 * 
	 * Speichern des ver�nderten Alarms - AlarmManager wird mit der selben ID
	 * �berschriebene, SharedPreferences werden gel�scht und neu angelegt.
	 * 
	 */
	public void save() {
		Intent intent = new Intent(this, AlarmReceiver.class);

		SharedPreferences sharedPreferences = getSharedPreferences("alarms", 0);
		Editor editor = sharedPreferences.edit();

		int hour = tp.getCurrentHour();
		int minute = tp.getCurrentMinute();

		cal.setTimeInMillis(cv.getDate());
		cal.set(Calendar.HOUR_OF_DAY, hour);
		cal.set(Calendar.MINUTE, minute);

		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
		String newDate = sdf.format(cal.getTime());

		editor.remove(id);
		editor.putString("" + id, newDate + ";" + description.getText() + ";"
				+ uriSelected + ";" + snooze.getSelectedItemPosition());
		editor.commit();

		intent.putExtra("id", Integer.parseInt(id));
		PendingIntent sender = PendingIntent.getBroadcast(this,
                Integer.parseInt(id), intent, 0);

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		Toast.makeText(this, "Alarm angelegt f�r " + cal.getTime(),
                Toast.LENGTH_LONG).show();

		finish();
		Intent alarm = new Intent(getBaseContext(), RemindMe.class);
		startActivity(alarm);

        //geändert
        finish();

	}

	/**
	 * 
	 * L�schen des ausgew�hlten Alarms, derzeit nicht in Verwendung, da das
	 * L�schen direkt in den AlarmTab ausgelagert wurde.
	 * 
	 */
	public void delete(View v) {
		SharedPreferences sharedPreferences = getSharedPreferences("alarms", 0);
		Editor editor = sharedPreferences.edit();
		editor.remove("" + id);
		editor.commit();
		Toast.makeText(this, "alarm deleted", Toast.LENGTH_LONG).show();

		Intent intent1 = new Intent(this, AlarmReceiver.class);
		PendingIntent sender1 = PendingIntent.getBroadcast(this,
                Integer.parseInt(id), intent1, 0);
		AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
		am1.cancel(sender1);

		Intent alarm = new Intent(getBaseContext(), RemindMe.class);
		startActivity(alarm);

        //geändert
        finish();

	}

	/**
	 * 
	 * RingtonePicker
	 * 
	 */
	public void setRingtone(View v) {

		Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE,
				"Select ringtone for notifications:");
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
				RingtoneManager.TYPE_NOTIFICATION);

		this.startActivityForResult(intent, 999);

	}

	/**
	 * 
	 * URI des selektierten Alarms wird in String gespeichert und in save() in
	 * die SharedPreferences gespeichert.
	 * 
	 */
	protected void onActivityResult(int requestCode, int resultCode,
			Intent Mringtone) {
		switch (resultCode) {

		case RESULT_OK:

			Uri uri = Mringtone
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

			Ringtone titel = RingtoneManager.getRingtone(this, uri);
			uriSelected = uri.toString();
			btnRingtone.setText(titel.getTitle(this));
			Log.i("Sample", "uri " + uri);
			break;
		}

	}

}
